package pers.xx.sbm.service.serviceImpl;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pers.xx.sbm.dao.DyReportDataMapper;
import pers.xx.sbm.service.DyReportDataService;
import pers.xx.sbm.vo.TotalSampleVo;

import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class DyReportDataServiceImpl implements DyReportDataService {

    @Autowired
    private DyReportDataMapper dyReportDataMapper;

    /**
     * 年份-1
     */
    private static int CURRENT_YEAR = LocalDate.now().getYear() - 1;

    /**
     * 总体
     */
    private List<TotalSampleVo> currentYearTotal = Collections.EMPTY_LIST;
    private List<TotalSampleVo> lastYearTotal = Collections.EMPTY_LIST;

    private double currentYear = 0.0;
    private double lastYear = 0.0;

    private int numbers = 0;

    /**
     * 小学
     */
    private List<TotalSampleVo> currentYearXTotal = Collections.EMPTY_LIST;
    private List<TotalSampleVo> lastYearXTotal = Collections.EMPTY_LIST;

    private double currentYearX = 0.0;
    private double lastYearX = 0.0;

    private int xNumbers = 0;

    private List<String> indexOrderX = new ArrayList<>();

    private LinkedHashMap<String,List<String>> indexMapX = new LinkedHashMap<>();
    /**
     * 初中
     */
    private List<TotalSampleVo> currentYearCTotal = Collections.EMPTY_LIST;
    private List<TotalSampleVo> lastYearCTotal = Collections.EMPTY_LIST;

    private double currentYearC = 0.0;
    private double lastYearC = 0.0;

    private int cNumbers = 0;

    private List<String> indexOrderC = new ArrayList<>();

    private LinkedHashMap<String,List<String>> indexMapC = new LinkedHashMap<>();
    /**
     * 高中
     */
    private List<TotalSampleVo> currentYearGTotal = Collections.EMPTY_LIST;
    private List<TotalSampleVo> lastYearGTotal = Collections.EMPTY_LIST;

    private double currentYearG = 0.0;
    private double lastYearG = 0.0;

    private int gNumbers = 0;

    private List<String> indexOrderG = new ArrayList<>();

    private LinkedHashMap<String,List<String>> indexMapG = new LinkedHashMap<>();


    private void inintNumber() {
        if (xNumbers != 0) {
            return;
        }
        List<Integer> numbersList = dyReportDataMapper.selectNumbers();
        if (CollectionUtils.isNotEmpty(numbersList)) {
            xNumbers = numbersList.get(0);
            cNumbers = numbersList.get(1);
            gNumbers = numbersList.get(2);
            numbers = xNumbers + cNumbers + gNumbers;
        }
    }

    @Override
    public String getAllSituationTxt() {
        initTotal();
        String result = "经监测，" + CURRENT_YEAR + "年贵阳市被监测年级学生品德发展水平平均得分" + currentYear + "，" + totalCompare(currentYear, lastYear) + "，" + areaCompareTotal(currentYearTotal, currentYear) + "。具体情况如下表 ：";
        return result;
    }

    @Override
    public Map<Integer, List<Object>> getAllSituationScore() {
        initTotal();
        Map<Integer, List<Object>> dataMap = new HashMap();
        dataMap.put(CURRENT_YEAR, currentYearTotal.stream().map(TotalSampleVo::getValue).collect(Collectors.toList()));
        dataMap.put(CURRENT_YEAR - 1, lastYearTotal.stream().map(TotalSampleVo::getValue).collect(Collectors.toList()));
        List<TotalSampleVo> totalSampleVos2 = dyReportDataMapper.queryTotalScore(CURRENT_YEAR - 2, "", "-1", "-1");
        dataMap.put(CURRENT_YEAR - 2, totalSampleVos2.stream().map(TotalSampleVo::getValue).collect(Collectors.toList()));
        List<TotalSampleVo> totalSampleVos3 = dyReportDataMapper.queryTotalScore(CURRENT_YEAR - 3, "", "-1", "-1");
        dataMap.put(CURRENT_YEAR - 3, totalSampleVos3.stream().map(TotalSampleVo::getValue).collect(Collectors.toList()));
        return dataMap;
    }

    @Override
    public String getDcdAllSituationTxtByXd(String xd) {
        initXdTotal(xd);
        String result = "经监测，贵阳市";
        if ("小学".equals(xd)) {
            result += "五年级学生品德发展水平平均得分" + currentYearX + "，" + xdCompare(currentYearX, lastYearX) + "，" + areaCompareTotal(currentYearXTotal, currentYearX) + "。情况如下图 ：";
        } else if ("初中".equals(xd)) {
            result += "八年级学生品德发展水平平均得分" + currentYearC + "，" + xdCompare(currentYearC, lastYearC) + "，" + areaCompareTotal(currentYearCTotal, currentYearC) + "。情况如下图 ：";
        } else {
            result += "高中二年级学生品德发展水平平均得分" + currentYearG + "，" + xdCompare(currentYearG, lastYearG) + "，" + areaCompareTotal(currentYearGTotal, currentYearG) + "。情况如下图 ：";
        }
        return result;
    }

    @Override
    public Map<Integer, List<Object>> getDcdAllSituationScoreByXd(String xd) {
        initXdTotal(xd);
        Map<Integer, List<Object>> dataMap = new HashMap();
        List<Object> currentYearList = Collections.EMPTY_LIST;
        List<Object> lastYearList = Collections.EMPTY_LIST;
        if ("小学".equals(xd)) {
            currentYearList = currentYearXTotal.stream().map(TotalSampleVo::getValue).collect(Collectors.toList());
            lastYearList = lastYearXTotal.stream().map(TotalSampleVo::getValue).collect(Collectors.toList());
        } else if ("初中".equals(xd)) {
            currentYearList = currentYearCTotal.stream().map(TotalSampleVo::getValue).collect(Collectors.toList());
            lastYearList = lastYearCTotal.stream().map(TotalSampleVo::getValue).collect(Collectors.toList());
        } else {
            currentYearList = currentYearGTotal.stream().map(TotalSampleVo::getValue).collect(Collectors.toList());
            lastYearList = lastYearGTotal.stream().map(TotalSampleVo::getValue).collect(Collectors.toList());
        }
        List<TotalSampleVo> YearAgo2 = dyReportDataMapper.queryTotalScore(CURRENT_YEAR - 2, "", "-1", xd);
        List<Object> YearAgo2List = YearAgo2.stream().map(TotalSampleVo::getValue).collect(Collectors.toList());
        List<TotalSampleVo> YearAgo3 = dyReportDataMapper.queryTotalScore(CURRENT_YEAR - 3, "", "-1", xd);
        List<Object> YearAgo3List = YearAgo3.stream().map(TotalSampleVo::getValue).collect(Collectors.toList());
        dataMap.put(CURRENT_YEAR, currentYearList);
        dataMap.put(CURRENT_YEAR - 1, lastYearList);
        dataMap.put(CURRENT_YEAR - 2, YearAgo2List);
        dataMap.put(CURRENT_YEAR - 3, YearAgo3List);
        return dataMap;
    }

    @Override
    public int getNumbers(String xd) {
        inintNumber();
        if ("小学".equals(xd)) {
            return xNumbers;
        } else if ("初中".equals(xd)) {
            return cNumbers;
        } else if ("高中".equals(xd)) {
            return gNumbers;
        } else {
            return numbers;
        }
    }

    @Override
    public List<Map<String, Object>> getTestContentByXd(String xd) {
        List<Map<String, Object>> data = new ArrayList<>();

        String[] orderNumber = {"①", "②", "③", "④", "⑤", "⑥", "⑦", "⑧", "⑨"};
        //获取学段对应所有一级指标
        List<String> indexNames = dyReportDataMapper.query1IndexNamesByXd(xd);
        if (CollectionUtils.isNotEmpty(indexNames)) {
            for (int i = 0; i < indexNames.size(); i++) {
                Map<String, Object> mapData = new HashMap<>();
                mapData.put("index", orderNumber[i] + indexNames.get(i) + "。");
                mapData.put("content", getContent(xd, indexNames.get(i)));
                Map<Integer, List<Double>> dataMap = new HashMap();
                List<Double> currentYearList = dyReportDataMapper.queryIndexTotalScoreHistory(CURRENT_YEAR, "", "-1", xd, indexNames.get(i));
                List<Double> lastYearList = dyReportDataMapper.queryIndexTotalScoreHistory(CURRENT_YEAR - 1, "", "-1", xd, indexNames.get(i));
                List<Double> lastYearAgoList = dyReportDataMapper.queryIndexTotalScoreHistory(CURRENT_YEAR - 2, "", "-1", xd, indexNames.get(i));
                if (CollectionUtils.isEmpty(currentYearList)) {
                    currentYearList = new ArrayList<>();
                    for (int j = 0; j < 12; j++) {
                        currentYearList.add(0.0);
                    }
                }
                if (CollectionUtils.isEmpty(lastYearList)) {
                    lastYearList = new ArrayList<>();
                    for (int j = 0; j < 12; j++) {
                        lastYearList.add(0.0);
                    }
                }
                if (CollectionUtils.isEmpty(lastYearAgoList)) {
                    lastYearAgoList = new ArrayList<>();
                    for (int j = 0; j < 12; j++) {
                        lastYearAgoList.add(0.0);
                    }
                }
                dataMap.put(CURRENT_YEAR, currentYearList);
                dataMap.put(CURRENT_YEAR - 1, lastYearList);
                dataMap.put(CURRENT_YEAR - 2, lastYearAgoList);
                mapData.put("score", dataMap);
                String detail = getDetail(xd, indexNames.get(i));
                mapData.put("detail", detail);
                data.add(mapData);
            }
        }

        return data;
    }

    @Override
    public List<Map<String, Object>> getCompareDataByXd(String xd) {
        List<Map<String, Object>> data = new ArrayList<>();
        //查询所有二级指标
        List<String> indexNames = new ArrayList<>();
        //二级指标排序
        if ("小学".equals(xd)) {
            indexNames = indexOrderX;
        } else if ("初中".equals(xd)) {
            indexNames = indexOrderC;
        } else if ("高中".equals(xd)) {
            indexNames = indexOrderG;
        }
        if (CollectionUtils.isNotEmpty(indexNames)) {
            for (String indexName : indexNames) {
                Map<String, Object> mapData = new HashMap<>();
                mapData.put("index", indexName);
                List<Double> currentYearList = dyReportDataMapper.query2IndexScoreHistory(CURRENT_YEAR, "", "-1", xd, indexName);
                List<Double> lastYearList = dyReportDataMapper.query2IndexScoreHistory(CURRENT_YEAR - 1, "", "-1", xd, indexName);
                if (CollectionUtils.isEmpty(lastYearList)) {
                    lastYearList = new ArrayList<>();
                    for (int i = 0; i < 12; i++) {
                        lastYearList.add(0.0);
                    }
                }
                mapData.put(CURRENT_YEAR + "", currentYearList);
                mapData.put(CURRENT_YEAR - 1 + "", lastYearList);
                List<Double> diff = getDiff(currentYearList, lastYearList);
                mapData.put("diff", diff);
                data.add(mapData);
            }
        }
        return data;
    }

    @Override
    public List<Map<String, Object>> getCompareTxtByXd(String xd) {
        List<Map<String, Object>> data = new ArrayList<>();

        LinkedHashMap<String,List<String>> indexMap = new LinkedHashMap<>();
        if ("小学".equals(xd)) {
            indexMap = indexMapX;
        } else if ("初中".equals(xd)) {
            indexMap = indexMapC;
        } else if ("高中".equals(xd)) {
            indexMap = indexMapG;
        }
        for(String index1Name:indexMap.keySet()) {
            Map<String, Object> mapData = new HashMap<>();
            mapData.put("index", index1Name);
            String txt = "";
            List<String> index2Names = indexMap.get(index1Name);
            for (String indexName : index2Names) {
                List<Double> currentYearList = dyReportDataMapper.query2IndexScoreHistory(CURRENT_YEAR, "", "-1", xd, indexName);
                List<Double> lastYearList = dyReportDataMapper.query2IndexScoreHistory(CURRENT_YEAR - 1, "", "-1", xd, indexName);
                txt += getDiffString(indexName,currentYearList,lastYearList);
            }
            mapData.put("diffTxt", txt.substring(0,txt.length() - 1) + "。");
            data.add(mapData);
        }
        return data;
    }

    private List<Double> getDiff(List<Double> currentYearList, List<Double> lastYearList) {
        if (CollectionUtils.isEmpty(currentYearList)) {
            for (int i = 0; i < 12; i++) {
                currentYearList.add(0.0);
            }
        }
        if (CollectionUtils.isEmpty(lastYearList)) {
            for (int i = 0; i < 12; i++) {
                lastYearList.add(0.0);
            }
        }
        List<Double> diff = new ArrayList<>();
        for (int i = 0; i < currentYearList.size(); i++) {
            if (0 == lastYearList.get(i)) {
                diff.add(0.0);
            } else {
                diff.add(Double.parseDouble(String.format("%.2f", currentYearList.get(i) - lastYearList.get(i))));
            }

        }
        return diff;
    }

    private String getDiffString(String indexName,List<Double> currentYearList, List<Double> lastYearList) {
        String[] area = {"云岩区","南明区","观山湖区","花溪区","乌当区","白云区","清镇市","修文县","开阳县","息烽县"};
        List<Double> currentList = currentYearList.subList(1, 11);
        String txt = "";
        if (CollectionUtils.isEmpty(lastYearList)) {
            txt =  "在" + indexName + "上，去年无数据;";
        }else {
            List<Double> lastList = lastYearList.subList(1, 11);
            List<String> up = new ArrayList<>();
            List<String> down = new ArrayList<>();
            List<String> keep = new ArrayList<>();
            for (int i = 0; i < currentList.size(); i++) {
                if (currentList.get(i).equals(lastList.get(i))) {
                    keep.add(area[i]);
                } else if(currentList.get(i) > lastList.get(i)){
                    up.add(area[i]);
                }else {
                    down.add(area[i]);
                }
            }
            if(up.size() == 10) {
                txt =  "在" + indexName + "上，10个区域均呈上升趋势;";
            }else if(down.size() == 10) {
                txt =  "在" + indexName + "上，10个区域均呈下降趋势;";
            }else {
                txt = "在" + indexName + "上，";
                if (CollectionUtils.isNotEmpty(up)) {
                    for (String name : up) {
                        txt += name + "、";
                    }
                    txt = txt.substring(0, txt.length() - 1) + "呈上升趋势，";
                }
                if (CollectionUtils.isNotEmpty(down)) {
                    for (String name : down) {
                        txt += name + "、";
                    }
                    txt = txt.substring(0, txt.length() - 1) + "呈下降趋势，";
                }
                if (CollectionUtils.isNotEmpty(keep)) {
                    for (String name : keep) {
                        txt += name + "、";
                    }
                    txt = txt.substring(0, txt.length() - 1) + "保持不变，";
                }
            }
        }
        return txt.substring(0,txt.length() - 1) + "；";
    }

    private String getDetail(String xd, String parentIndexName) {
        String result = "其中，";
        List<TotalSampleVo> data = dyReportDataMapper.query2IndexScoreByXd(xd, parentIndexName, CURRENT_YEAR);
        if (CollectionUtils.isEmpty(data)) {
            return result;
        }
        List<String> index2Name = new ArrayList<>();
        List<String> indexNames = dyReportDataMapper.query2IndexNameByXd(xd, CURRENT_YEAR);
        for (TotalSampleVo vo : data) {
            String indexName = vo.getName();
            if ("小学".equals(xd) && indexOrderX.size() != indexNames.size()) {
                indexOrderX.add(indexName);
            } else if ("初中".equals(xd) && indexOrderC.size() != indexNames.size()) {
                indexOrderC.add(indexName);
            } else if ("高中".equals(xd) && indexOrderG.size() != indexNames.size()) {
                indexOrderG.add(indexName);
            }
            index2Name.add(indexName);
            Double score = Double.valueOf(vo.getValue().toString());
            result += "在" + indexName + "层面的平均得分为" + score + "，" + getResult(score) + ";";
        }
        if ("小学".equals(xd)) {
            indexMapX.put(parentIndexName,index2Name);
        } else if ("初中".equals(xd)) {
            indexMapC.put(parentIndexName,index2Name);
        } else if ("高中".equals(xd)) {
            indexMapG.put(parentIndexName,index2Name);
        }
        return result.substring(0, result.length() - 1) + "。";
    }

    private String getContent(String xd, String indexName) {
        double score = dyReportDataMapper.queryScoreByXdAndIndexName(xd, indexName, CURRENT_YEAR);
        String result = "";
        if ("小学".equals(xd)) {
            result += "全市五年级监测对象在" + indexName + "方面的平均得分为" + score + "," + getResult(score);
        } else if ("初中".equals(xd)) {
            result += "全市八年级监测对象在" + indexName + "方面的平均得分为" + score + "," + getResult(score);
        } else {
            result += "全市高中二年级监测对象在" + indexName + "方面的平均得分为" + score + "," + getResult(score);
        }
        return result;
    }

    private String getResult(double score) {
        //4分以上视为答题效果非常符合教育预期，3-4分视为答题效果基本达到教育预期
        String result = "";
        if (score != 0) {
            if (score >= 4) {
                result = "非常符合教育预期";
            } else if (score > 3 && score < 4) {
                result = "基本达到教育预期";
            } else {
                result = "未达到教育预期";
            }
        }
        return result;
    }

    private void initXdTotal(String xd) {
        if ("小学".equals(xd)) {
            if (CollectionUtils.isEmpty(currentYearXTotal)) {
                currentYearXTotal = dyReportDataMapper.queryTotalScore(CURRENT_YEAR, "", "-1", xd);
            }
            if (CollectionUtils.isNotEmpty(currentYearXTotal)) {
                currentYearX = Double.parseDouble(currentYearXTotal.get(0).getValue().toString());
            }
            if (CollectionUtils.isEmpty(lastYearXTotal)) {
                lastYearXTotal = dyReportDataMapper.queryTotalScore(CURRENT_YEAR - 1, "", "-1", xd);
            }
            if (CollectionUtils.isNotEmpty(lastYearXTotal)) {
                lastYearX = Double.parseDouble(lastYearXTotal.get(0).getValue().toString());
            }
        } else if ("初中".equals(xd)) {
            if (CollectionUtils.isEmpty(currentYearCTotal)) {
                currentYearCTotal = dyReportDataMapper.queryTotalScore(CURRENT_YEAR, "", "-1", xd);
            }
            if (CollectionUtils.isNotEmpty(currentYearCTotal)) {
                currentYearC = Double.parseDouble(currentYearCTotal.get(0).getValue().toString());
            }
            if (CollectionUtils.isEmpty(lastYearCTotal)) {
                lastYearCTotal = dyReportDataMapper.queryTotalScore(CURRENT_YEAR - 1, "", "-1", xd);
            }
            if (CollectionUtils.isNotEmpty(lastYearCTotal)) {
                lastYearC = Double.parseDouble(lastYearCTotal.get(0).getValue().toString());
            }
        } else {
            if (CollectionUtils.isEmpty(currentYearGTotal)) {
                currentYearGTotal = dyReportDataMapper.queryTotalScore(CURRENT_YEAR, "", "-1", xd);
            }
            if (CollectionUtils.isNotEmpty(currentYearGTotal)) {
                currentYearG = Double.parseDouble(currentYearGTotal.get(0).getValue().toString());
            }
            if (CollectionUtils.isEmpty(lastYearGTotal)) {
                lastYearGTotal = dyReportDataMapper.queryTotalScore(CURRENT_YEAR - 1, "", "-1", xd);
            }
            if (CollectionUtils.isNotEmpty(lastYearGTotal)) {
                lastYearG = Double.parseDouble(lastYearGTotal.get(0).getValue().toString());
            }
        }

    }

    private void initTotal() {
        if (CollectionUtils.isEmpty(currentYearTotal)) {
            currentYearTotal = dyReportDataMapper.queryTotalScore(CURRENT_YEAR, "", "-1", "-1");
        }
        if (CollectionUtils.isNotEmpty(currentYearTotal)) {
            currentYear = Double.parseDouble(currentYearTotal.get(0).getValue().toString());
        }
        if (CollectionUtils.isEmpty(lastYearTotal)) {
            lastYearTotal = dyReportDataMapper.queryTotalScore(CURRENT_YEAR - 1, "", "-1", "-1");
        }
        if (CollectionUtils.isNotEmpty(lastYearTotal)) {
            lastYear = Double.parseDouble(lastYearTotal.get(0).getValue().toString());
        }
    }

    private String totalCompare(double currentYearValue, double lastYearValue) {
        String compareTxt = "";
        if (currentYearValue > lastYearValue) {
            compareTxt = "高于" + (CURRENT_YEAR - 1) + "年，";
        } else if (currentYearValue < lastYearValue) {
            compareTxt = "低于" + (CURRENT_YEAR - 1) + "年，";
        } else {
            compareTxt = "等于" + (CURRENT_YEAR - 1) + "年，";
        }
        String totalTxt = xdCompare(currentYearValue, lastYearValue);
        return compareTxt + totalTxt;
    }

    private String xdCompare(double currentYearValue, double lastYearValue) {
        String compareTxt = "";
        if (currentYearValue >= 80) {
            compareTxt = "总体上处于上水平，非常符合教育预期";
        } else if (currentYearValue >= 60 && currentYearValue < 80) {
            compareTxt = "总体上处于中上水平，基本达到教育预期";
        } else {
            compareTxt = "总体上处于中下水平，未达到教育预期";
        }
        return compareTxt;
    }

    private String areaCompareTotal(List<TotalSampleVo> currentYearTotal, double currentYear) {
        if (CollectionUtils.isEmpty(currentYearTotal)) {
            return "";
        }
        List<TotalSampleVo> up = currentYearTotal.stream().filter(vo -> !vo.getName().equals("全市") && Double.parseDouble(vo.getValue().toString()) > currentYear).collect(Collectors.toList());
        List<TotalSampleVo> down = currentYearTotal.stream().filter(vo -> !vo.getName().equals("全市") && Double.parseDouble(vo.getValue().toString()) < currentYear).collect(Collectors.toList());
        List<TotalSampleVo> keep = currentYearTotal.stream().filter(vo -> !vo.getName().equals("全市") && Double.parseDouble(vo.getValue().toString()) == currentYear).collect(Collectors.toList());

        String result = "";

        if (up.size() != 0 && down.size() == 0 && keep.size() == 0) {
            result = "全市十个区（市、县）中，学生德育发展水平监测得分较高。";
        } else if (up.size() == 0 && down.size() != 0 && keep.size() == 0) {
            result = "全市十个区（市、县）中，学生德育发展水平监测处于全市平均水平以下。";
        } else {
            result = "全市十个区（市、县）中，";
            if (up.size() != 0) {
                for (TotalSampleVo vo : up) {
                    result += vo.getName();
                    result += "、";
                }
                result = result.substring(0, result.length() - 1);
                result += "学生德育发展水平监测得分较高，";
            }

            if (down.size() != 0) {
                for (TotalSampleVo vo : down) {
                    result += vo.getName();
                    result += "、";
                }
                result = result.substring(0, result.length() - 1);
                result += "处于全市平均水平以下，";
            }
            if (keep.size() != 0) {
                for (TotalSampleVo vo : keep) {
                    result += vo.getName();
                    result += "、";
                }
                result = result.substring(0, result.length() - 1);
                result += "与全市平均水平一致，";
            }
            result = result.substring(0, result.length() - 1);
        }

        return result;
    }
}
